//
//  FansRankContentViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/10/12.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "FansRankContentViewController.h"
#import "RankTableViewCell.h"
#import "User.h"
#import "HomeServer.h"

@interface FansRankContentViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;


@end

@implementation FansRankContentViewController {
    UITableView *_tableView;
    RankTableViewCell *_cell;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.page = 1;
    
    [self GETRankLists];
    
    [self buildUI];
    
//    [self refreshData];
    
}


#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    self.navigationItem.title = self.titleName;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-64-44) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    
    [_tableView setSeparatorColor:UISeparatedColorRGB];
    
    [_tableView registerNib:[UINib nibWithNibName:@"RankTableViewCell" bundle:nil] forCellReuseIdentifier:@"rank"];
    
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETRankLists];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETRankLists];
    }];
    
}


#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"rank"];

    _cell.rank.text = [NSString stringWithFormat:@"%ld", indexPath.row+1];
    
    User *model = self.infoArr[indexPath.row];
    _cell.model = model;
    
    _cell.optionsBtn.tag = indexPath.row+1;
    [_cell.optionsBtn addTarget:self action:@selector(fansAction:) forControlEvents:UIControlEventTouchUpInside];
    
    _cell.preservesSuperviewLayoutMargins = NO;
    _cell.separatorInset = UIEdgeInsetsZero;
    _cell.layoutMargins = UIEdgeInsetsZero;
    
    return _cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //    return _cell.sepView.y+_cell.sepView.height;
    return SW(8)+20;
    //    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
}


#pragma mark ===========响应方法==========
/**
 获取资讯列表
 */
- (void)GETRankLists {
    
    // GET /articles 获取（查询）资讯列表 keyword 关键词，匹配商品名 page 页码，默认为1 per_page 每页显示数，默认为10 cate_id 二级分类ID，暂不支持一级分类搜索 orderby 排序字段
    
    NSDictionary *param = @{@"limit":@"30",
                            @"anchor_id":self.userId,
                            @"type":self.keyWord};
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/ranklists/followers", APIUser, self.userId];
    
    [[NetworkTool sharedTool] requestWithName:@"获取粉丝贡献榜" URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
        
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        
        for (NSDictionary *dic in arr) {
            User *model = [[User alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}


/**
 添加关注 or 取消关注
 */
- (void)fansAction:(UIButton *)sender {
    
    User *model = self.infoArr[sender.tag-1];
    NSString *toId = [model valueForKey:@"user_id"];
    
    [HomeServer focus:sender toId:toId];
}


// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
